package me.duzhi.ilog.cms.function;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jfinal.log.Log;
import java.util.Map;
import java.util.Properties;


/**
 * Created by Qinjin on 2017/7/16.
 */
public class SFTPKit {

  Session session = null;
  Channel channel = null;


  public static final String SFTP_REQ_HOST = "sftp.host";
  public static final String SFTP_REQ_PORT = "sftp.port";
  public static final String SFTP_REQ_USERNAME = "sftp.username";
  public static final String SFTP_REQ_PASSWORD = "sftp.password";
  public static final int SFTP_DEFAULT_PORT = 22;
  public static final String SFTP_REQ_LOC = "location";
  public static final Log LOG = Log.getLog(SFTPKit.class);

  public ChannelSftp getChannel(Map<String, String> sftpDetails, int timeout) throws JSchException {

    String ftpHost = sftpDetails.get(SFTP_REQ_HOST);
    String port = sftpDetails.get(SFTP_REQ_PORT);
    String ftpUserName = sftpDetails.get(SFTP_REQ_USERNAME);
    String ftpPassword = sftpDetails.get(SFTP_REQ_PASSWORD);

    int ftpPort = SFTP_DEFAULT_PORT;
    if (port != null && !port.equals("")) {
      ftpPort = Integer.valueOf(port);
    }

    JSch jsch = new JSch(); // 创建JSch对象
    session = jsch.getSession(ftpUserName, ftpHost, ftpPort); // 根据用户名，主机ip，端口获取一个Session对象

    if (LOG.isDebugEnabled()) {
      LOG.debug("Session created.");
    }
    if (ftpPassword != null) {
      session.setPassword(ftpPassword); // 设置密码
    }
    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config); // 为Session对象设置properties
    session.setTimeout(timeout); // 设置timeout时间
    session.connect(); // 通过Session建立链接
    if (LOG.isDebugEnabled()) {
      LOG.debug("Session connected.");
    }

    LOG.debug("Opening Channel.");
    channel = session.openChannel("sftp"); // 打开SFTP通道
    channel.connect(); // 建立SFTP通道的连接
    if (LOG.isDebugEnabled()) {
      LOG.debug(
          "Connected successfully to ftpHost = " + ftpHost + ",as ftpUserName = " + ftpUserName
              + ", returning: " + channel);
    }

    return (ChannelSftp) channel;
  }

  public void closeChannel() throws Exception {
    if (channel != null) {
      channel.disconnect();
    }
    if (session != null) {
      session.disconnect();
    }
  }
}
